home *** CD-ROM | disk | FTP | other *** search
- Path: rcp6.elan.af.mil!rscernix!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: C beginner needs your help ASAP
- Date: 19 Feb 96 00:24:49 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.824689489@rscernix>
- References: <4g862f$p0b@risky.ecs.umass.edu> <4g8ahd$p8b@spectator.cris.com>
- NNTP-Posting-Host: ues5.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <4g8ahd$p8b@spectator.cris.com> aubrey@concentric.net (Aubrey Harrison) writes:
-
- >This is how I would do it. I tested it and it seems to do what you want. Of
- ^^^^^^^^
- "It seems" is the keyword here, indeed.
-
- >course, I am no expert, in fact I was called "ignorant and idiot" by Mister Dan
-
- Not only you're no expert, you have also difficulties counting up to ten.
-
- >#include <stdio.h>
- >
- >main()
- >{
- > char buf[3],filename[9];
- > int i;
- >
- > for(i=0; i<10; i++)
- > {
- > sprintf(buf,"%d",i);
- > strcpy( filename,"data");
- > strcat( filename, buf );
- > strcat( filename, ".ext");
-
- strcat and strcpy are _not_ functions returning an int, hence a proper
- declaration is mandatory (even if the value returned is discarded).
- ALWAYS include <string.h> before using string manipulation functions.
-
- Anyway, these 4 lines can be replaced by a single sprintf call:
-
- sprintf(buf, "data%d.ext", i);
-
- > printf( "%s\n", filename);
- > }
- Returning a value from a function (implicitly) defined as returning int
- is always a good idea.
- >}
-
- Let's look at how buf and filename are dimensioned.
-
- buf will always hold one digit and the terminating null character. It's
- oversized by one character, but this not a major problem. Better safe
- than sorry :-)
-
- OTOH, we're in deep trouble with filename, which will have to contain
- strings of the form "dataX.ext", but sizeof "dataX.ext" is 10, not 9.
- Now we're invoking undefined behaviour and we should be sorry for this :-)
-
- Too many mistakes in such a short and simple program, don't you think?
- Badly written code is of no help to anybody. First learn C _yourself_,
- then try to help others.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-